package com.llsydn.demo.appList;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.ScaleAnimation;
import android.widget.*;
import com.llsydn.hello.R;

import java.util.ArrayList;
import java.util.List;

/**
 * @author lilinshen
 * @title 显示手机的所有应用列表
 * @description 请填写相关描述
 * @date 2018/9/21 14:21
 */
public class ListActivity extends AppCompatActivity implements View.OnClickListener {

    private ListView lv_main_1;
    private List<AppInfo> data;
    private AppAdapter appAdapter;
    private PopupWindow pw;
    private View pwView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list);

        //初始化成员变量
        lv_main_1 = findViewById(R.id.lv_main_1);
        data = getAllAppInfos();
        appAdapter = new AppAdapter();

        //显示列表
        lv_main_1.setAdapter(appAdapter);

        //设置点击监听事件
        lv_main_1.setOnItemClickListener(((parent, view, position, id) -> {
            //parent:ListView，view：当前行的item视图对象，position：当前行的下标
            //提示当前行的应用名称
            String appName = data.get(position).getAppName();
            //Toast.makeText(ListActivity.this, appName, Toast.LENGTH_SHORT).show();
            if (pw == null) {
                pwView = View.inflate(ListActivity.this, R.layout.pw_layout, null);
                pw = new PopupWindow(pwView, view.getWidth() - 140, view.getHeight() -5);
                //必须要指定背景图片，不然动画不生效。
                pw.setBackgroundDrawable(new BitmapDrawable());

                //得到子view设置点击监听
                pwView.findViewById(R.id.ll_pw_uninstall).setOnClickListener(ListActivity.this);
                pwView.findViewById(R.id.ll_pw_run).setOnClickListener(ListActivity.this);
                pwView.findViewById(R.id.ll_pw_share).setOnClickListener(ListActivity.this);
            }
            //如果正在显示
            if (pw.isShowing()) {
                pw.dismiss();
            }
            //显示
            pw.showAsDropDown(view, 90, -view.getHeight());
            //添加动画
            ScaleAnimation animation = new ScaleAnimation(0, 1, 0, 1);
            animation.setDuration(1000);
            pwView.startAnimation(animation);
        }));

        //设置长按事件监听
        lv_main_1.setOnItemLongClickListener(((parent, view, position, id) -> {
            //删除当前行
            data.remove(position);
            //更新列表（通知更新列表，会使用所有缓存的item的视图对象）
            appAdapter.notifyDataSetChanged();
            //lv_main_1.setAdapter(appAdapter); 不会使用缓存的
            return true;
        }));

        //设置滑动滚动条监听
        lv_main_1.setOnScrollListener(new AbsListView.OnScrollListener() {
            /**
             * SCROLL_STATE_IDLE 空闲，不动状态
             * SCROLL_STATE_TOUCH_SCROLL 跟着手指滚动
             * SCROLL_STATE_FLING 快速滚动
             *
             * @param view
             * @param scrollState
             */
            //当listview的滚动状态发生改变时调用
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (scrollState == SCROLL_STATE_TOUCH_SCROLL) {
                    //移除正在显示的pw
                    if (pw != null && pw.isShowing()) {
                        pw.dismiss();
                    }
                }
            }

            //当listview正在滚动时调用（产生move时不断调用）
            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });
    }

    /**
     * 子view的点击事件监听
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_pw_uninstall:
                pw.dismiss();
                Toast.makeText(this, "卸载", Toast.LENGTH_SHORT).show();
                break;
            case R.id.ll_pw_run:
                pw.dismiss();
                Toast.makeText(this, "运行", Toast.LENGTH_SHORT).show();
                break;
            case R.id.ll_pw_share:
                pw.dismiss();
                Toast.makeText(this, "分享", Toast.LENGTH_SHORT).show();
                break;
            default:
                break;
        }
    }

    /**
     * 自定义的baseAdapter
     */
    class AppAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return data.size();
        }

        @Override
        public Object getItem(int position) {
            return data.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        //返回带数据当前行的Item视图对象
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            //1.如果convertView为null，加载item的布局文件
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = View.inflate(ListActivity.this, R.layout.item_main, null);
                holder.imageView = convertView.findViewById(R.id.iv_item_icon);
                holder.textView = convertView.findViewById(R.id.tv_item_name);
                //将holder保存在convertView上
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            //2.得到当前行数据对象
            AppInfo appInfo = data.get(position);
            //得到当前行需要更新的子view对象
            ImageView imageIcon = holder.imageView;
            TextView textAppName = holder.textView;
            //3.给视图设置数据
            imageIcon.setImageDrawable(appInfo.getIcon());
            textAppName.setText(appInfo.getAppName());
            //4.返回视图
            return convertView;
        }
    }

    /**
     * 获取手机所有应用信息的列表
     *
     * @return
     */
    protected List<AppInfo> getAllAppInfos() {
        List<AppInfo> list = new ArrayList<AppInfo>();
        //得到应有的packageManager
        PackageManager packageManager = getPackageManager();
        //创建一个主界面的Intent
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        //得到包含应用信息的列表
        List<ResolveInfo> resolveInfoList = packageManager.queryIntentActivities(intent, 0);
        //遍历
        for (ResolveInfo resolveInfo : resolveInfoList) {
            //得到相应的信息
            String packageName = resolveInfo.activityInfo.packageName;
            Drawable icon = resolveInfo.loadIcon(packageManager);
            String appName = resolveInfo.loadLabel(packageManager).toString();
            //封装成AppInfo对象，并添加到list集合中
            AppInfo appInfo = new AppInfo(icon, appName, packageName);
            list.add(appInfo);
        }
        return list;
    }

    //子视图对象
    class ViewHolder {
        private ImageView imageView;
        private TextView textView;
    }
}
